<template>
  <!--  模板管理  -->
  <div class="dictMapping app-container">
    <el-row :gutter="20" class="full-row">
      <!--左侧数据-->
      <div class="full-height" style="padding: 20px;">
        <el-input v-model="filterText" prefix-icon="el-icon-search" placeholder="输入关键字进行过滤" maxlength="100" clearable @keyup.enter.native="handleFilter(filterText)" @clear="handleFilter(filterText)" />
        <div class="head-container" style="flex: 1; overflow: auto">
          <div class="title hk-flex" @click="handleFilterAll">
            <div class="tit-left">
              <i :class="showchild ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" />
              <span>类型</span>
            </div>
            <el-button type="text" icon="el-icon-plus" @click.stop="() => append()" />
          </div>
          <el-tree
            v-show="showchild"
            ref="tree"
            :expand-on-click-node="false"
            default-expand-all
            :data="deptOptions"
            :props="defaultProps"
            current-node-key="1"
            :filter-node-method="filterNode"
            node-key="id"
            :highlight-current="isHightlight"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" style="width: 90%; display: flex">
              <span v-if="!data.showInput" class="custom-tree-node" style="width: 100%;">
                <span v-if="data.itemLabel.length < 13">{{ data.itemLabel }}</span>
                <el-tooltip v-else class="item" effect="dark" :content="data.itemLabel" placement="top">
                  <span
                    style="overflow: hidden;
                    text-overflow:ellipsis;
                    white-space: nowrap;"
                  >{{ data.itemLabel }}</span>
                </el-tooltip>
                <i v-show="data.flag != false">
                  <!-- <el-button
                    v-if="data.isLeaf == 0"
                    type="text"
                    size="mini"
                    icon="el-icon-plus"
                    @click.stop="() => append(data)" /> -->
                  <el-button type="text" size="mini" icon="el-icon-edit" @click.stop="() => editNode(node, data)" />
                  <el-button type="text" size="mini" icon="el-icon-delete" @click.stop="() => delNode(node, data)" />
                </i>
              </span>
              <span v-else class="custom-tree-node">
                <el-input v-model="data.itemLabel" placeholder="不能为空" maxlength="255" size="mini" class="innerput" />
                <i>
                  <el-button type="text" size="mini" @click.stop="() => sureNode(node, data)"> 确定 </el-button>

                  <el-button type="text" size="mini" @click.stop="() => remove(node, data)"> 取消 </el-button>
                </i>
              </span>
            </span>
          </el-tree>
        </div>
      </div>
      <!-- 表格  -->
      <div class="user">
        <HkSearchform
          :data="queryParams"
          :field-list="filterInfo.fieldList"
          label-width="200px"
          @handleSearch="handleQuery"
          @handleReset="resetQuery"
        />

        <el-row :gutter="10" class="mt2">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增 </el-button>
            <el-button size="mini" icon="el-icon-delete" style="margin-left:10px !important;" :disabled="ids.length == 0" @click="handleDel">删除 </el-button>
          </el-col>
        </el-row>
        <HkTable
          style="flex: 1; overflow: auto"
          :loading="loading"
          :table-data="tableData"
          :table-columns="tableList"
          :selection="true"
          :operate="true"
          :total="total"
          :table-height="80"
          :show-index="true"
          :operate-width="200"
          :query-params="queryParams"
          @handleSelectionChange="handleSelectionChange"
          @changePage="getListData"
        >
          <template #operate="scope">
            <el-button size="mini" type="text" @click="handlePreview(scope.row)">预览 </el-button>
            <el-button v-if="scope.row.isPreset!='1'" size="mini" type="text" @click="handleEdit(scope.row)">编辑 </el-button>
            <el-button size="mini" type="text" @click="handleCopy(scope.row)">复制</el-button>
            <el-button
              v-show="scope.row.isPreset != '1'"
              size="mini"
              type="text"
              @click="handleDel(scope.row)"
            >删除
            </el-button>
          </template>
          <template #templateType="scope">
            <span
              style="overflow: hidden;
                  text-overflow:ellipsis;
                  white-space: nowrap;"
            >{{ setTemplateType(scope.row.templateType) }}</span>
          </template>
        </HkTable>
      </div>
    </el-row>
    <!-- 新增弹窗 -->
    <addDialog ref="addDialogRef" :template-type-options="deptOptions" :title="title" @handleSubmit="getListData()" />
  </div>
</template>

<script>
import {
  queryPageList,
  delTemplate,
  copyTemplate,
  getTemplateType,
  addTemplateType,
  editTemplateType,
  delTemplateType
} from '@/api/riskProduct/templateManage'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import HkTable from '@/components/HKTable/index'
import HkSearchform from '@/components/HKSearchform/index.vue'
import addDialog from './addDialog.vue'
import { parseTime } from '@/utils/hongke'

export default {
  name: 'TemplateManage',
  components: {
    HkTable,
    HkSearchform,
    addDialog
  },
  data() {
    return {
      // 是否显示搜索条件
      showchild: true,
      // 是否是添加状态
      appendState: false,
      // 字典维护所需要的
      upholdId: '',
      dictCode: '',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // 总条数
      total: 0,
      // 部门列表
      deptOptions: [],
      // 表格数据
      tableData: [],
      // 弹出层标题
      title: '',
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        startTime: '',
        endTime: ''
      },
      // 搜索项配置
      filterInfo: {
        fieldList: [
          { label: '模板名称/创建人', type: 'input', field: 'keyword', maxlength: 100 },
          {
            label: '更新时间',
            type: 'dateRange',
            field: 'updateRange'
          }
        ]
      },
      //  表格
      tableList: [
        { label: '模板名称', param: 'templateName' },
        { label: '类型', param: 'templateType', type: 'slot' },
        { label: '创建人', param: 'creator' },
        { label: '生成时间', param: 'createTime' },
        { label: '更新时间', param: 'updateTime' }
      ],
      defaultProps: {
        children: 'children',
        label: 'itemLabel'
      },

      // 表单校验
      rules: {},
      filterText: '',
      isHightlight: false
    }
  },
  // watch: {
  //   filterText(val) {

  //   }
  // },
  created() {
    this.getTreeselect()
    this.handleQuery()
  },

  methods: {
    //  左侧筛选
    handleFilter(val) {
      this.$refs.tree.filter(val)
    },
    // 查詢全部
    handleFilterAll() {
      this.isHightlight = false
      // this.showchild = !this.showchild
      this.queryParams.templateType = null
      this.getListData()
    },
    // 增加节点
    append() {
      this.appendState = true
      const newChild = { name: '', children: [] }
      newChild.showInput = true
      newChild.remove = true
      this.deptOptions.unshift(newChild)
    },
    // 确定添加树节点
    sureNode(node, data) {
      this.appendState = false
      if (data.itemLabel) {
        if (data?.id) {
          editTemplateType({ itemLabel: data.itemLabel, groupId: data.groupId, id: data.id }).then((res) => {
            this.$message.success('更新成功')
            this.getTreeselect()
            data.showInput = false
            data.remove = true
          })
        } else {
          addTemplateType({ label: data.itemLabel }).then((res) => {
            this.$message.success('新增成功')
            this.getTreeselect()
            data.showInput = false
            data.remove = true
          })
        }
      } else {
        this.$message.error('名称不能为空')
      }
    },
    // 重命名node
    editNode(node, data) {
      data.remove = false
      data.showInput = true
      data.oldItemLabel = data.itemLabel
    },
    // 取消修改树节点
    remove(node, data) {
      if (data.id) {
        data.remove = true
        data.showInput = false
        data.itemLabel = data.oldItemLabel
      } else {
        this.deptOptions.shift(data)
      }
    },
    //  删除节点
    delNode(node, data) {
      delTemplateType(data.id).then((res) => {
        this.$message.success('删除成功')
        this.getTreeselect()
      })
    },
    // 获取所有字典名称
    handleQuery(val) {
      this.queryParams.current = 1
      this.queryParams.keyword = val?.keyword
      this.queryParams.updateRange = val?.updateRange

      this.getListData()
    },

    /** 查询列表 */
    getListData(val) {
      this.loading = true
      if (this.queryParams.updateRange) {
        this.queryParams.startTime = parseTime(this.queryParams.updateRange[0])
        this.queryParams.endTime = parseTime(this.queryParams.updateRange[1])
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
      this.queryParams.scrollToTop = true
      queryPageList(this.queryParams).then((res) => {
        this.total = res.total
        this.tableData = res.list
        this.loading = false
        this.queryParams.scrollToTop = false
      })
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
    },
    /** 查询模板类型 */
    getTreeselect() {
      return new Promise((resolve, reject) => {
        getTemplateType().then((res) => {
          this.deptOptions = res.map((item) => {
            return {
              children: this.treeChild(item.children),
              itemLabel: item.itemLabel,
              id: item.id,
              groupId: item.groupId,
              itemVale: item.itemVale,
              showInput: false,
              remove: true,
              flag: item.flag
            }
          })
          resolve(this.deptOptions)
        })
      })
    },
    // 递归数据
    treeChild(item) {
      if (item) {
        return item.map((i) => {
          return {
            children: this.treeChild(i.children),
            dictKey: i.dictKey,
            id: i.id,
            showInput: false,
            remove: true
          }
        })
      } else return
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.itemLabel.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      return new Promise((resolve, reject) => {
        this.isHightlight = true
        this.queryParams.templateType = data.itemVale
        resolve(this.queryParams)
      }).then(() => {
        this.getListData()
      })
    },
    // 右侧新增完成
    handleSubmit() {
      this.getListData()
      this.getTreeselect()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.addDialogRef.show('add')
      this.title = '新增'
    },
    // 预览
    handlePreview(row) {
      window.open(`/dispose-api/reportTemplate/preview?id=${row.id}`)
    },
    //  编辑
    handleEdit(row) {
      this.title = '编辑'
      this.$refs.addDialogRef.show('edit', row.id, row.isPreset)
    },
    //  复制
    handleCopy(row) {
      copyTemplate(row.id).then((res) => {
        this.$message.success('复制成功')
        this.getListData()
      })
    },
    //  删除
    handleDel(row) {
      const _this = this
      this.$modal
        .confirm('是否确认删除此数据吗？')
        .then(function() {
          if (row.id) {
            return delTemplate(row.id)
          } else {
            const delIds = _this.ids.join(',')
            return delTemplate(delIds)
          }
        })
        .then((res) => {
          this.$modal.msgSuccess(res)
          this.getListData()
        })
        .catch((error) => {})
    },
    //  类型转义
    setTemplateType(type) {
      let typeLabel = ''
      for (let i = 0; i < this.deptOptions.length; i++) {
        if (this.deptOptions[i].itemVale === type) {
          typeLabel = this.deptOptions[i].itemLabel
          break
        }
      }
      return typeLabel
    }
  }
}
</script>
<style lang="scss" scoped>
.el-button + .el-button {
  margin-left: 0px !important;
}
::v-deep .el-table__row .el-button--mini{
  padding:5px 5px;
}
::v-deep .el-loading-mask{
  z-index:999 !important;
}
::v-deep .el-icon-circle-plus {
  font-size: 16px !important;
}
.app-container {
  padding: 0;
}
.user {
  padding: 20px;
  width: calc(100% - 270px);
  height: 100%;
  display: flex;
  flex-direction: column;
}
.full-row {
  width: 100%;
  display: flex;
  margin: 0 !important;
  height: 100%;

  .full-height {
    height: 100%;
    display: flex;
    width: 270px;
    flex-direction: column;
    border-right: 1px solid rgba(0, 0, 0, 0.08);
    .head-container {
      margin-top: 10px;
      overflow-x:hidden !important;
      .title {
        cursor: pointer;
        font-size: 14px;
        padding: 5px 10px !important;
        background: #f8f8f8;
        .tit-left {
          flex: 1;
          span {
            margin-left: 10px;
          }
        }
      }
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    overflow: hidden !important;
    .el-button--mini{
      padding:8px 5px !important;
    }
  }
}
.innerput::v-deep input {
  // width: 100px;
  font-size: 14px;
  padding: 0 5px;
}
</style>
<style lang="scss">
.dictMapping {
  width: 100%;
  height: 100%;
  .el-tree {
    margin-top: 10px;
    font-size: 14px;
  }
}
</style>
